var qcloud = require('../../../vendor/sdk/index');
var config = require('../../../config');
var app = getApp();

Page({
  data: {
    navH: app.globalData.navHeight,
    fileHost: app.globalData.imageUrl,
    theme: config.theme,
    auditProgram: false,
    modalVisible: false,
    unPassedReason: '',
    userInfo: null,
    programLogo: '',
    programLogoUrl: '',
    id: '',
    name: '',
    tags: '',
    startTime: '',
    endTime: '',
    programDesc: '',
    errorMsg: '输入错误',
    showTopTips: false,
    countText: '0/300',
    nameWarn: false,
    tagsWarn: false,
    startTimeWarn: false,
    endTimeWarn: false,
    repeatWarn: false,
    isPublish: false,
    repeat: 'day1',
    repeatText: '周一',
    items: [
      { name: '名称', value: '名称' },
      { name: '标签', value: '标签' },
      { name: '内容', value: '内容' },
      { name: '简介', value: '简介' },
      { name: '封面', value: '封面' },
      { name: 'logo', value: 'logo' }
    ],
    categorys: [],
    visits: ['隐藏', '展示'],
    objectCategorys: [],
    categoryId: 0,
    categoryDefaultIndex: 0,
    visitsDefaultIndex: 1,
    submtButtonText: '发布',
  },
  onLoad(option) {
    app.getUserInfo().then(userInfo => {
      this.setData({
        userInfo
      });
    });
    let repeatEnum = {
      day1: '周一',
      day2: '周二',
      day3: '周三',
      day4: '周四',
      day5: '周五',
      day6: '周六',
      day7: '周天'
    };

    if (option.program) {
      let auditProgram = option.audit && option.audit;
      let p = JSON.parse(option.program);
      let visitsDefaultIndex = 1;
      if (p.visit==0 || p.visit==1) {
        visitsDefaultIndex = p.visit;
      } else if (p.visitsDefaultIndex == 0 || p.visitsDefaultIndex == 1) {
        visitsDefaultIndex = p.visitsDefaultIndex;
      }
      this.setData({
        id: p.id,
        name: p.name,
        tags: p.tags,
        startTime: p.startTime,
        endTime: p.endTime,
        categoryId: p.categoryId,
        categoryDefaultIndex: p.categoryDefaultIndex == undefined ? this.data.categoryDefaultIndex : p.categoryDefaultIndex,
        visitsDefaultIndex,
        programDesc: p.programDesc,
        programLogoUrl: this.data.fileHost + p.programLogo,
        programLogo: p.programLogo,
        coverImg: p.coverImg,
        coverImgUrl: this.data.fileHost + p.coverImg,
        repeat: p.repeat,
        repeatText: p.repeat && p.repeat.split(',').map(v => repeatEnum[v]),
        auditProgram: auditProgram && auditProgram ? true : false
      });
    }
    this.getCategoryList();
  },
  onNavBack() {
    // 返回
    // wx.navigateBack();
    wx.redirectTo({
      url: `/pages/personalPage/personalPage`
    });
  },
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      categoryDefaultIndex: e.detail.value
    })
  },
  bindVisitChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      visitsDefaultIndex: e.detail.value
    })
  },
  getCategoryList() {
    qcloud.request({
      url: config.service.getCategoryListUrl,
      data: {},
      success: res => {
        let categoryList = res.data.data.categories;
        if (categoryList && categoryList.length > 0) {
          let categorys = categoryList.map(item => item.categoryName);
          let objectCategorys = categoryList.map(item => { return { id: item.id, name: item.categoryName}});
          let categoryDefaultIndex = this.data.categoryDefaultIndex;
          let targetCategory = categoryList.forEach((item, index) => {
            if (item.id === this.data.categoryId) {
              categoryDefaultIndex = index;
            }
          });
          this.setData({
            categorys: categorys,
            objectCategorys: objectCategorys,
            categoryDefaultIndex: categoryDefaultIndex,
          });
        }
      },
      fail: err => {
      }
    });
  },
  auditPassed() {
    // 审核通过
    qcloud.request({
      url: config.service.auditProgramUrl,
      data: {
        programId: this.data.id,
        auditStatus: 2
      },
      success: function (res) {
        wx.showToast({
          title: res.data.success ? '审核成功' : '审核失败!请联系管理员',
          icon: res.data.success ? 'success' : 'none',
          duration: 2000
        });
        setTimeout(() => {
          wx.redirectTo({
            url: '../personalPage'
          });
        }, 2000);
      }
    });
  },
  auditUnPassed() {
    if (!this.data.unPassedReason) {
      wx.showToast({
        title: '请勾选不通过项',
        icon: 'none',
        image: '',
        duration: 1500,
        mask: false
      });
      return;
    }
    // 审核不通过
    qcloud.request({
      url: config.service.auditProgramUrl,
      data: {
        programId: this.data.id,
        auditStatus: 3,
        auditResult: this.data.unPassedReason
      },
      success: function (res) {
        wx.showToast({
          title: res.data.success ? '提交成功' : '提交失败!请联系管理员',
          icon: res.data.success ? 'success' : 'none',
          duration: 2000
        });
        setTimeout(() => {
          wx.redirectTo({
            url: '../personalPage'
          });
        }, 2000);
      }
    });
  },
  auditunPassedReasonChange(e) {
    this.setData({
      unPassedReason: e.detail.value && e.detail.value.join(';')
    });
  },
  showModalAuditUnPassed() {
    // 显示未通过modal框填写未通过原因
    this.setData({
      modalVisible: true
    });
  },
  hideAuditUnPassedModal() {
    // 隐藏未通过modal框填写未通过原因
    this.setData({
      modalVisible: false
    });
  },
  goToRepeat() {
    // 重复选择
    let {
      name,
      tags,
      startTime,
      endTime,
      programDesc,
      repeat,
      programLogo,
      id,
      coverImg,
      categoryId,
      categoryDefaultIndex,
      visitsDefaultIndex,
    } = this.data;
    wx.navigateTo({
      url:
        './repeat?repeat=' +
        repeat +
        '&program=' +
        JSON.stringify({
          name,
          id,
          tags,
          startTime,
          endTime,
          programDesc,
          programLogo,
          coverImg,
          categoryId,
          categoryDefaultIndex,
          visitsDefaultIndex
        })
    });
  },
  startTimeChange(e) {
    // 开始时间
    this.setData({
      startTime: e.detail.value,
      startTimeWarn: false
    });
  },
  endTimeChange(e) {
    // 结束时间
    this.setData({
      endTime: e.detail.value,
      endTimeWarn: false
    });
  },
  nameChange(e) {
    // 互动名称change
    this.setData({ name: e.detail.value, nameWarn: false });
  },
  tagsChange(e) {
    // 互动标签change
    this.setData({ tags: e.detail.value, tagsWarn: false });
  },
  programDescChange(e) {
    // 互动简介change
    this.setData({
      programDesc: e.detail.value,
      countText: e.detail.value.length + '/300'
    });
  },
  uploadCoverImg() {
    // 互动图片chagne
    this.chooseImage('coverImg');
  },
  uploadLogo() {
    // 上传logo
    this.chooseImage('programLogo');
  },
  chooseImage(filed) {
    // 选择照片并上传
    let self = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        var tempFilePaths = res.tempFilePaths;
        wx.uploadFile({
          url: config.service.uploadFileUrl,
          filePath: tempFilePaths[0],
          name: 'file',
          formData: {},
          success: function (res) {
            let data = JSON.parse(res.data).data;
            self.setData({
              [filed]: data.path,
              [filed + 'Url']: self.data.fileHost + data.path,
            });
          }
        });
      }
    });
  },
  validateData(v) {
    // 表单验证
    let result = {
      nameWarn: !v.name || v.name.length > 10,
      startTimeWarn: !v.startTime,
      endTimeWarn: !v.endTime,
    };
    if (!v.coverImg) {
      this.showError('请上传封面');
    } else if (!v.name.length > 30) {
      this.showError('名称不能超过30个字符');
    }

    this.setData({ ...result });

    return (
      v.coverImg &&
      !result.nameWarn &&
      !result.startTimeWarn &&
      !result.endTimeWarn
    );
  },
  showError(msg) {
    // 展示错误信息
    this.setData({ errorMsg: msg || '输入错误', showTopTips: true });
    let self = this;
    setTimeout(() => self.setData({ showTopTips: false }), 2000);
  },
  formSubmit(e) {
    // 表单提交
    this.setData({ isPublish: true, submtButtonText: '发布中...' });
    var self = this;
    var formData = e.detail.value;
    const data = {
      ...formData,
      userId: self.data.userInfo.id,
      userName: self.data.userInfo.name,
      logo: self.data.programLogo,
      coverImg: self.data.coverImg,
      id: self.data.id,
      status: 2,
      startTime: self.data.startTime,
      endTime: self.data.endTime,
      repeat: self.data.repeat,
      categoryId: self.data.objectCategorys[self.data.categoryDefaultIndex].id,
      visit: self.data.visitsDefaultIndex,
    };

    let isPass = this.validateData(data);
    if (isPass !== true) {
      this.setData({ isPublish: false });
      return;
    }

    qcloud.request({
      url: config.service.saveProgramUrl,
      method: 'post',
      data,
      success: function (res) {
        if (res.statusCode == 200) {
          wx.navigateTo({
            url: './publishSuccess/publishSuccess?data=' + res.data.data
          });
        }
      }
    });
  }
});
